Page({
  data: {
    speed: 120,
    brightness: 100,
    discoColor: '#7f5fff',
    showSlider: false,
    showBackBtn: true,
    hideTimer: null,
    discoTimer: null,
    colorList: [],
    useAll: false
  },
  onLoad(query) {
    let useAll = false;
    let colorList = [];
    if (query.colors === 'all') {
      useAll = true;
    } else if (query.colors) {
      colorList = decodeURIComponent(query.colors).split(',').map(c => c.trim()).filter(Boolean);
    }
    this.setData({ useAll, colorList });
    this.setData({
      speed: Number(query.speed) || 120,
      brightness: Number(query.brightness) || 100
    });
    this.startDisco();
    this.startAutoHide();
  },
  startDisco() {
    if (this.data.discoTimer) clearInterval(this.data.discoTimer);
    let idx = 0;
    this.data.discoTimer = setInterval(() => {
      let color = '#7f5fff';
      if (this.data.useAll) {
        // 全色系随机
        const h = Math.floor(Math.random() * 360);
        const s = 80 + Math.floor(Math.random() * 20);
        const l = 45 + Math.floor(Math.random() * 10);
        color = `hsl(${h},${s}%,${l}%)`;
      } else if (this.data.colorList.length > 0) {
        color = this.data.colorList[idx % this.data.colorList.length];
        idx++;
      }
      this.setData({ discoColor: color });
    }, Math.max(20, 220 - (this.data.speed || 120)));
  },
  startAutoHide() {
    if (this.data.hideTimer) clearTimeout(this.data.hideTimer);
    this.data.hideTimer = setTimeout(() => {
      this.setData({ showSlider: false, showBackBtn: false });
    }, 1000);
  },
  toggleSlider(e) {
    if (e && e.target && e.target.dataset && e.target.dataset.btn) return;
    if (this.data.hideTimer) clearTimeout(this.data.hideTimer);
    this.setData({ showSlider: true, showBackBtn: true });
    this.startAutoHide();
  },
  onSpeedChange(e) {
    this.setData({ speed: e.detail.value });
    this.startDisco();
  },
  onSpeedChanging(e) {
    this.setData({ speed: e.detail.value });
    this.startDisco();
  },
  onBrightnessChanging(e) {
    this.setData({ brightness: e.detail.value });
    if (this.data.hideTimer) clearTimeout(this.data.hideTimer);
    this.startAutoHide();
  },
  onBrightnessChange(e) {
    this.setData({ brightness: e.detail.value });
  },
  goBack() {
    wx.navigateBack();
  },
  onUnload() {
    if (this.data.hideTimer) clearTimeout(this.data.hideTimer);
    if (this.data.discoTimer) clearInterval(this.data.discoTimer);
  }
}); 